package com.zyt.filter;

import com.zyt.utils.CurrentHolder;
import com.zyt.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1. 获取请求参数
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2.获取请求路径
        String requestURI = request.getRequestURI();

        //3.判断是否为登录请求,如果是登录请求,则放行
        if(requestURI.contains("login")){
            log.info("登录请求,放行");
            filterChain.doFilter(request,response);
            return;
        }
        //4.获取请求头中的token
        String token = request.getHeader("token");

        //5.判断是否有 token,如果无token,则拦截,返回状态码:401
        if(token == null || token.isEmpty()){
            log.info("令牌为空,拦截");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //6.解析token,如果解析失败,则拦截,返回状态码:401
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前员工id:{}",empId);
        } catch (Exception e) {
            log.info("令牌非法,拦截");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //7.解析成功,则放行
        log.info("令牌解析成功,放行");
        filterChain.doFilter(request,response);

        CurrentHolder.remove();
    }
}
